package com.baseframe.user.controller;


import cn.hutool.core.util.DesensitizedUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baseframe.auth.utils.AuthUtil;
import com.baseframe.mybatis.utils.PageInfo;
import com.baseframe.sms.constant.BaseSmsSendConstant;
import com.baseframe.tool.result.R;
import com.baseframe.tool.utils.redis.CommonRedisUtil;
import com.baseframe.user.entity.BaseUser;
import com.baseframe.user.entity.request.BaseUserRequest;
import com.baseframe.user.entity.vo.BaseUserVO;
import com.baseframe.user.service.BaseUserService;
import com.baseframe.user.service.SnsUserRelationService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/front/user")
@AllArgsConstructor
public class FrontBaseUserController {

    private BaseUserService baseUserService;

    private SnsUserRelationService snsUserRelationService;

    /**
     * 新用户注册
     * @param request
     * @return
     */
    @PostMapping("/register")
    public R<Object> register(@RequestBody BaseUserRequest request){
        if(request.getCode() == null){
            return R.fail("缺少必要请求参数");
        }
        //验证验证码
        String redisCode = CommonRedisUtil.getValue(BaseSmsSendConstant.SMS_CAPTCHA_REDIS_KEY+request.getPhone());
        CommonRedisUtil.delete(BaseSmsSendConstant.SMS_CAPTCHA_REDIS_KEY+request.getPhone());

        if(redisCode==null){
            return R.fail("验证码已过期~");
        }

        if(!redisCode.equals(request.getCode())){
            return R.fail("验证码错误~");
        }
        //判断手机号码是否已经被其他账号绑定
        BaseUser one = baseUserService.getOne(new LambdaQueryWrapper<BaseUser>().eq(BaseUser::getPhone, request.getPhone()));
        if(one!=null){
            return R.fail("该手机号码已经绑定了其他账号,请取消绑定之后重试~");
        }

        //判断用户名是否存在
        one = baseUserService.getOne(new LambdaQueryWrapper<BaseUser>().eq(BaseUser::getUsername,request.getUsername()));

        if(one!=null){
            return R.fail("该用户名已经存在，请修改用户名后重试~");
        }

        return baseUserService.register(request)?R.success():R.fail();
    }




    /**
     * 绑定邮箱
     * @param request 用户对象
     * @return R
     */
    @PostMapping("/binding/email")
    public R<Object> bindingEmail(@RequestBody BaseUserRequest request){

        if (request.getNewEmail()==null||request.getOldEmail()==null){
            return R.fail("缺少必要请求参数");
        }

        BaseUser baseUser = baseUserService.getById(AuthUtil.getUserId());

        String email = baseUser.getEmail();

        if(!request.getOldEmail().equals(email)){

            return R.fail("输入的邮箱与绑定的邮箱不一致");
        }

        BaseUser one = baseUserService.getOne(new LambdaQueryWrapper<BaseUser>().eq(BaseUser::getEmail, request.getNewEmail()));

        if(one!=null){
            return R.fail(String.format("电子邮箱：%s已经绑定过其他账户，请解除绑定后继续操作~",request.getNewEmail()));
        }

        return baseUserService.bindingEmail(request)?R.success():R.fail();
    }


    /**
     * 绑定手机号码
     * @param request
     * @return
     */
    @PostMapping("/binding/phone")
    public R<Object> bindingPhone(@RequestBody BaseUserRequest request){
        if (request.getNewPhone()==null||request.getOldPhone()==null){
            return R.fail("缺少必要请求参数");
        }

        BaseUser baseUser = baseUserService.getById(AuthUtil.getUserId());

        String phone = baseUser.getPhone();

        if(!request.getOldPhone().equals(phone)){

            return R.fail("输入的手机号码与原先实际绑定的手机号码不一致");
        }

        BaseUser one = baseUserService.getOne(new LambdaQueryWrapper<BaseUser>().eq(BaseUser::getPhone, request.getNewPhone()));

        if(one!=null){
            return R.fail(String.format("手机号码：%s已经绑定过其他账户，请解除绑定后继续操作~",request.getNewPhone()));
        }


        return baseUserService.bindingPhone(request)?R.success():R.fail();
    }


    /**
     * 搜索用户
     * @param searchValue
     * @return
     */
    @GetMapping("/search")
    public R<Object> searchUser(String searchValue){
        List<BaseUserVO> userVOList = baseUserService.searchUser(searchValue);
        userVOList.forEach(e->{
            e.setPassword(null);
            //获取用户关系
            e.setFollow(snsUserRelationService.hasFollow(AuthUtil.getUserId(),e.getId()));
        });
        return R.data(userVOList);
    }

    @PostMapping("/update")
    public R<Object> updateUserInfo(@RequestBody BaseUserRequest request){

        return baseUserService.updateUserinfo(request)?R.success():R.fail();
    }

    /**
     *获取用户信息（登录之后）
     */
    @GetMapping("/details")
    public R<BaseUserVO> getUserInfo(){
        Long userId = AuthUtil.getUserId();
        BaseUserVO userInfo = baseUserService.getUserInfo(userId);
        userInfo.setPassword(null);
        // jyc:调连
        userInfo.setFullPhone(userInfo.getPhone());
        //敏感数据脱敏
        if(userInfo.getEmail()!=null){
            userInfo.setEmail(DesensitizedUtil.email(userInfo.getEmail()));
        }
        if(userInfo.getPhone()!=null){
            userInfo.setPhone(DesensitizedUtil.mobilePhone(userInfo.getPhone()));
        }
        userInfo.setGenderName(userInfo.getGender()==1?"男":"女");

        return R.data(userInfo);
    }

    /**
     * 重置密码
     * @param request
     * @return
     */
    @PostMapping("/reset/password")
    public R<Object> resetPassword(@RequestBody BaseUserRequest request){


        return baseUserService.resetPassword(request);
    }


}
